//
//  StrategyModelDataSource.swift
//  travelMapMvvm-swift2
//
//  Created by green on 15/11/3.
//  Copyright © 2015年 travelMapMvvm-swift2. All rights reserved.
//

import Foundation
import ReactiveCocoa
import AFNetworking
import TMCommonLib
import JSONHelper

public class StrategyModelDataSource: StrategyModelDataSourceProtocol {
    
    public class func shareInstance()->StrategyModelDataSourceProtocol{
        struct YRSingleton{
            static var predicate:dispatch_once_t = 0
            static var instance:StrategyModelDataSource? = nil
        }
        dispatch_once(&YRSingleton.predicate,{
            YRSingleton.instance=StrategyModelDataSource()
        })
        return YRSingleton.instance!
    }
    
    // MARK: - 系统推荐攻略
    
    public func queryStrategyListBySystem(pageIndex: Int, pageSize: Int, sortCode: String?, strategyTypeCode: String?, strategyThemeCodes: [String]?, monthCodes: [String]?) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in
            
            var parameters: [String:AnyObject] = [
                "pageIndex"     : pageIndex,
                "pageSize"      : pageSize
            ]
            
            if let sortCode=sortCode {
                
                parameters["sort"] = sortCode
            }
            
            if let strategyTypeCode=strategyTypeCode {
                
                parameters["articleType"] = strategyTypeCode
            }
            if let strategyThemeCodes=strategyThemeCodes where strategyThemeCodes.count != 0  {
                
                parameters["kingTag"] = covertToString(strategyThemeCodes)
            }
            if let monthCodes=monthCodes where monthCodes.count != 0 {
                
                parameters["travelSeason"] = covertToString(monthCodes)
            }
            
            let manager = AFHTTPRequestOperationManager()
            manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html","text/plain"]) as Set<NSObject>
            
            manager.GET(kURL+"GetArticleList", parameters: parameters, success: { (operation, responseObj) -> Void in
                
                let resultDic = responseObj as! [NSObject:AnyObject]
                
                let success             = resultDic[kSuccess] as? Int
                let msg                 = resultDic[kMsg] as? String
                
                if success == 0 {
                    
                    var strategyModels:[StrategyModel]?
                    
                    strategyModels <-- resultDic[kData]
                    
                    subscriber.sendNext(strategyModels)
                    subscriber.sendCompleted()
                    
                } else {
                    
                    subscriber.sendError(DataError.QueryStrategyListBySystemError(msg).error)
                }
                
            }) { (operation, error) -> Void in
                
                subscriber.sendError(DataError.QueryStrategyListBySystemError(nil).error)
            }
            
            return nil
        })
    }
    
    // MARK: - 关键字攻略
    
    public func queryStrategyListByKeyword(pageIndex: Int, pageSize: Int, sortCode: String?, keyword: String) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in
            
            var parameters: [String:AnyObject] = [
                "pageIndex"     : pageIndex,
                "pageSize"      : pageSize,
                "keyword"       : keyword
            ]
            
            if let sortCode=sortCode {
                
                parameters["sort"] = sortCode
            }
            
            let manager = AFHTTPRequestOperationManager()
            manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html","text/plain"]) as Set<NSObject>
            
            manager.GET(kURL+"getarticlelistbykeyword", parameters: parameters, success: { (operation, responseObj) -> Void in
                
                let resultDic = responseObj as! [NSObject:AnyObject]
                
                let success             = resultDic[kSuccess] as? Int
                let msg                 = resultDic[kMsg] as? String
                
                if success == 0 {
                    
                    var strategyModels:[StrategyModel]?
                    
                    strategyModels <-- resultDic[kData]
                    
                    subscriber.sendNext(strategyModels)
                    subscriber.sendCompleted()
                    
                } else {
                    
                    subscriber.sendError(DataError.QueryStrategyListByKeywordError(msg).error)
                }
                
            }) { (operation, error) -> Void in
                
                subscriber.sendError(DataError.QueryStrategyListByKeywordError(nil).error)
            }
            
            return nil
        })
    }
    
    // MARK: - 已收藏的攻略
    
    public func queryStrategyListByUserId(pageIndex: Int, pageSize: Int, sortCode: String?, userId: Int) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in
            
            var parameters: [String:AnyObject] = [
                "pageIndex"     : pageIndex,
                "pageSize"      : pageSize,
                "userId"        : userId
            ]
            
            if let sortCode=sortCode {
                
                parameters["sort"] = sortCode
            }
            
            let manager = AFHTTPRequestOperationManager()
            manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html","text/plain"]) as Set<NSObject>
            
            manager.GET(kURL+"getarticlelist", parameters: parameters, success: { (operation, responseObj) -> Void in
                
                let resultDic = responseObj as! [NSObject:AnyObject]
                
                let success             = resultDic[kSuccess] as? Int
                let msg                 = resultDic[kMsg] as? String
                
                if success == 0 {
                    
                    var strategyModels:[StrategyModel]?
                    
                    strategyModels <-- resultDic[kData]
                    
                    subscriber.sendNext(strategyModels)
                    subscriber.sendCompleted()
                    
                } else {
                    
                    subscriber.sendError(DataError.QueryStrategyListByUserIdError(msg).error)
                }
                
            }) { (operation, error) -> Void in
                
                subscriber.sendError(DataError.QueryStrategyListByUserIdError(nil).error)
            }
            
            return nil
        })
    }
    
    // MARK: - 收藏攻略/取消收藏
    
    public func collectStrategy(strategyId: String, userId: Int, isFavorite: Bool) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in
            
            let parameters: [String:AnyObject] = [
                "articleId"    : strategyId,
                "userId"       : userId,
                "isFavorite"   : String(isFavorite)
            ]
            
            let manager = AFHTTPRequestOperationManager()
            manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html","text/plain"]) as Set<NSObject>
            
            manager.POST(kURL+"setFavoriteArticle", parameters: parameters, success: { (operation, responseObj) -> Void in
                
                let resultDic = responseObj as! [NSObject:AnyObject]
                
                let success             = resultDic[kSuccess] as? Int
                let msg                 = resultDic[kMsg] as? String
                
                if success == 0 {
                    
                    subscriber.sendNext(kSuccess)
                    subscriber.sendCompleted()
                    
                } else {
                    
                    subscriber.sendError(DataError.CollectStrategyError(msg).error)
                }
                
            }) { (operation, error) -> Void in
                
                subscriber.sendError(DataError.CollectStrategyError(nil).error)
            }
            
            return nil
        })
    }
    
    // MARK: - 喜欢攻略/取消喜欢
    
    public func likeStrategy(strategyId: String, userId: Int, isLike: Bool) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber:RACSubscriber!) -> RACDisposable! in
            
            let parameters: [String:AnyObject] = [
                "strategyId"    : strategyId,
                "userId"        : userId,
                "isLike"        : String(isLike)
            ]
            
            let manager = AFHTTPRequestOperationManager()
            manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html","text/plain"]) as Set<NSObject>
            
            manager.POST(kURL+"setLikeArticle", parameters: parameters, success: { (operation, responseObj) -> Void in
                
                let resultDic = responseObj as! [NSObject:AnyObject]
                
                let success             = resultDic[kSuccess] as? Int
                let msg                 = resultDic[kMsg] as? String
                
                if success == 0 {
                    
                    subscriber.sendNext(kSuccess)
                    subscriber.sendCompleted()
                    
                } else {
                    
                    subscriber.sendError(DataError.LikeStrategyError(msg).error)
                }
                
                }) { (operation, error) -> Void in
                    
                    subscriber.sendError(DataError.LikeStrategyError(nil).error)
            }
            
            return nil
        })
    }
    
}